/***@author wangmu***/
/***5-10 10:30***/
var dire = angular.module("shop.directive", ["shop.services"]);
//var login_html = APIURL + "wap/login.php?referer="  + location.href;
var login_html = APIURL + "wap/login.php?referer=" + encodeURI(location.href);
var loginUrl = function(a) {
    return window.location.href = a + "?referer=" + encodeURIComponent(location.href);
}
dire.directive("shop", ["$routeParams", '$sce', "$http", "surplusDay", function($routeParams, $sce, http, surplusDay) { // 游戏列表
    return {
        templateUrl: "templates/groupbuy/shop.html",
        restrict: "E",
        link: function(scope, element, attrs) {
            var product_id = $routeParams.product_id;
            switching(".oneCategory>li", ".twoCategory>li", "active", "phptoCurr"); //页面切换    //店铺首页分类切换
            switchingSlide(".shopCenter .choice>ul>li", ".topSelect>li", "active", "phptoCurr"); //页面切换//店铺首页导航切换   
            activeClick(".twoCategory .twoCategoryList li", "active");
            activeClick(".distAddress li", "active");
            activeClick(".ranking li", "active");
            $("#city_4").citySelect({});
            console.log(111);
            http({
                method: 'GET',
                url: APIURL + 'app.php?c=goods&app=app&a=game&product_id=' + product_id //游戏列表
            }).success(function(data) {
                console.log(data);
                if (data.err_code == 20000) {
                    window.location = login_html;
                }
                scope.game = data.err_msg;
            });
        }
    }
}]);
dire.directive("detail", ["$routeParams", '$sce', "$http", "surplusDay", function($routeParams, $sce, http, surplusDay) { // 详情页面
    return {
        templateUrl: "templates/groupbuy/details.html",
        restrict: "E",
        link: function(scope, element, attrs) {

            var product_id = $routeParams.product_id;
            var store_id = $routeParams.store_id;
            http({
                method: 'GET',
                url: APIURL + 'app.php?c=goods&app=app&a=index&id=' + product_id + '&store_id=' + store_id //选择支付类型
            }).success(function(data) {
                    if (data.err_code == 20000) {
                        return loginUrl(data.err_msg);
                    }
                    if (data.err_code == 0) {
                        scope.APIURL = APIURL;
                        switching(".productInfoList .title li", ".productInfoList .productInfo>li", "active", "phptoCurr"); //页面切换  //详情页面
                        scope.product = data.err_msg;
                        scope.detailtext = $sce.trustAsHtml(scope.product.product.info); //图文信息
                        scope.fx_dataTxt = $sce.trustAsHtml(scope.product.fx_data.msg); //分销信息
                        scope.discountMsg = function(a) {
                            return $sce.trustAsHtml(a);
                        };
                        scope.fxShow = true;
                        scope.fxBttton = function(a) { //设置分销按钮文本以及是否显示
                            if (a == "OTHER") {
                                return "#/createShop/" + scope.product.product.store_id;
                            } else if (a == "FX") {
                                return "#/distributionShop/" + product_id + "/" + scope.product.fx_data.store_id;
                            } else {
                                scope.fxShow = false;
                            };
                        };
                        scope.showTxt = function(a) { //判断是否显示
                            if (a * 1 == 0) {
                                return false;
                            } else {
                                return true;
                            };
                        };
                        scope.like = function(a) { //判断是否喜欢
                            if (a == 0) {
                                return "";
                            } else if (a == 1) {
                                return "active";
                            };
                        };
                        scope.postage = function(a) { //判断邮费
                            if (scope.product.product.postage == 0) {
                                scope.product.product.postage = "包邮";
                            }
                            if (a == 0) {
                                return scope.product.product.postage;
                            } else {
                                if (scope.product.product.postage_tpl == undefined) {
                                    return scope.product.product.postage;
                                } else {
                                    return scope.product.product.postage_tpl.min + "~" + scope.product.product.postage_tpl.max;
                                };
                            };
                        };

                        scope.credit_arrIcon = function(a) { //标签图标
                            switch (a) {
                                case "RZ":
                                    return "证";
                                    break;
                                case "7D":
                                    return "退";
                                    break;
                                case "DB":
                                    return "保";
                                    break;
                                case "MD":
                                    return "店";
                                    break;
                            }
                            //21, 117
                        };
                        /*
                        window._bd_share_config = { //分享代码
                            "common": {
                                "bdSnsKey": {},
                                "bdText": "",
                                "bdMini": "2",
                                "bdMiniList": false,
                                "bdPic": "",
                                "bdStyle": "0",
                                "bdSize": "16"
                            },
                            "share": {}
                        };
                        with(document) 0[(getElementsByTagName('head')[0] || body).appendChild(createElement('script')).src = 'http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion=' + ~(-new Date() / 36e5)];

                        function Rad(d) {
                            return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
                        }
                        //计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
                        function GetDistance(lat1, lng1, lat2, lng2) {
                            var radLat1 = Rad(lat1);
                            var radLat2 = Rad(lat2);
                            var a = radLat1 - radLat2;
                            var b = Rad(lng1) - Rad(lng2);
                            var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
                            s = s * 6378.137; // EARTH_RADIUS;
                            s = Math.round(s * 10000) / 10000; //输出为公里
                            s = s.toFixed(4);
                            return s;
                        }
                        /*
                        var B1 = 31.818855;
                        var B2 = 117.217105;
                          */
                        //var d = 111.12 * Math.cos(1 / (Math.sin(A2) * Math.sin(B2) + Math.cos(A2) * Math.cos(B2) * Math.cos(B1 - A1)));
                        /*   navigator.geolocation.getCurrentPosition( // 该函数有如下三个参数  //经纬度
                               function(pos) { // 如果成果则执行该回调函数
                                   /*   alert(
                                          '  经度：' + pos.coords.latitude +
                                          '  纬度：' + pos.coords.longitude
                                       );*/
                        /*   var A1 = scope.product.send_data.long;
                            var A2 = scope.product.send_data.lat;
                            var B1 = pos.coords.latitude;
                            var B2 = pos.coords.longitude;
                            var distance = GetDistance(A1, A2, B1, B2) / 5000;
                            if (distance < 3) {
                                return "今日";
                            };

                        },
                        function(err) { // 如果失败则执行该回调函数

                        }, { // 附带参数
                            enableHighAccuracy: false, // 提高精度(耗费资源)
                            timeout: 3000, // 超过timeout则调用失败的回调函数
                            maximumAge: 1000 // 获取到的地理信息的有效期，超过有效期则重新获取一次位置信息
                        }
                    );
*/
                        scope.likeClick = function(a) {
                            http({
                                method: 'GET',
                                url: APIURL + 'app.php?c=collect&a=add&type=1&dataid=' + product_id + '&store_id=' + store_id //选择支付类型
                            }).success(function(data) {
                                console.log(data);
                                if (data.err_code == 0) {
                                    return scope.like = function(a) {
                                        return "active";
                                    };
                                }
                            });
                        };
                        scope.recordListTime = function(a) { //时间戳转换格式
                            return surplusDay.convertTime(a);
                        };
                        scope.receiveCoupon = function() {
                            http({
                                method: 'GET',
                                url: APIURL + 'app.php?c=coupon&app=app&store_id=' + store_id //优惠券列表
                            }).success(function(data) {
                                console.log(data);
                                scope.receiveList = data.err_msg;

                            });
                        }
                        scope.receive = function(a) {
                            http({
                                method: 'GET',
                                url: APIURL + 'app.php?c=coupon&app=app&a=collect&coupon_id=' + a //领取优惠券
                            }).success(function(data) {
                                if (data.err_code == 0) {
                                    $(".coupon .promptTxt").fadeToggle('300');
                                    setTimeout(function() {
                                        $(".coupon .promptTxt").fadeToggle('300');
                                    }, 1000);
                                };

                            });
                        };



                        scope.shoppingRecord = function() { //购买记录
                            http({
                                method: 'GET',
                                url: APIURL + 'app.php?c=goods&app=app&a=buy_list&product_id=' + product_id //购买记录
                            }).success(function(data) {
                                scope.recordList = data.err_msg;
                                var url = "app.php?c=goods&app=app&a=buy_list&product_id=" + product_id;
                                var page = 0;
                                var flge = true;
                                //surplusDay.loadJson(++i, scope.recordList.order_list, url); //下拉列表加载数据
                                angular.element(document).on("scroll", function() { // 滚动加载数据
                                    var hi = $(".recordTxt").offset().top;
                                    var window_hight = $(window).height() + $(window).scrollTop();
                                    if (hi <= window_hight + 20) {
                                        if (flge) { //判断是否有下一页
                                            surplusDay.init(url, ++page).success(function(data) {
                                                if (data.err_msg.next_page) {
                                                    for (var i = 0; i < data.err_msg.order_list.length; i++) {
                                                        scope.shopIndex.order_list.push(data.err_msg.order_list[i]);
                                                    }
                                                } else {

                                                    return flge = false;
                                                }
                                            });
                                        } else {

                                        }
                                    }
                                
                                /*******************/
                            });
                        });
                }; 
                scope.productComment = function(a) {
                    var i = 0;
                    var url = 'app.php?c=comment&app=app&a=comment_list&type=PRODUCT&data_id=' + product_id + '&tab=' + a;
                    http({
                        method: 'GET',
                        url: APIURL + url //评论列表
                    }).success(function(data) {
                        scope.commentList = data.err_msg;

                        //surplusDay.loadJson(++i, scope.commentList.comment_list, url); //下拉列表加载数据
                        var page = 0;
                        var flge = true;
                        angular.element(document).on("scroll", function() { // 滚动加载数据
                            var hi = $(".commentTxt").offset().top;
                            var window_hight = $(window).height() + $(window).scrollTop();
                            if (hi <= window_hight + 20) {
                                if (flge) { //判断是否有下一页
                                    surplusDay.init(url, ++page).success(function(data) {
                                        if (data.err_msg.next_page) {
                                            for (var i = 0; i < data.err_msg.comment_list.length; i++) {
                                                scope.shopIndex.comment_list.push(data.err_msg.comment_list[i]);
                                            }
                                        } else {

                                            return flge = false;
                                        }
                                    });
                                } else {

                                }
                            }
                        });
                        /*******************/
                    });
                }; scope.shppingButton = function(type, b) { //底部购物车按钮
                    scope.shoppingNum = 1;
                    http({
                        method: 'GET',
                        url: APIURL + 'app.php?c=goods&app=app&a=info&product_id=' + product_id + '&store_id=' + store_id //选择支付类型
                    }).success(function(data) {
                        if (data.err_code = 1000) {};
                        scope.shopping = data.err_msg;
                        scope.shoppingActive = function(a) { //判断是否是默认
                            if (a == 0) {
                                return "active";
                            };
                        };
                        scope.shoppingValue = function(a) { //获取父元素eq,传值
                            var index = $(event.target).parents(".productLabelList").index();
                            $(".productName p i").eq(index - 2).text(a);
                        };
                        scope.plus = function() { //减数量
                            scope.shoppingNum++;
                        };
                        scope.reduce = function() { //加数量
                            if (scope.shoppingNum > 1) {
                                scope.shoppingNum--;
                            };
                        };
                        var value = [];
                        scope.shoppingCat = function() { //加入购物车
                            var length = $(".shoppingCat .productName p i");
                            for (var i = 0; i < length.length; i++) {
                                value[i] = length.eq(i).text();
                            }
                            var data = {
                                type: type,
                                name: scope.shopping.product.name,
                                price: scope.shopping.product.price,
                                number: scope.shoppingNum,
                                value: value
                            };

                        };
                    });
                };
            }

        });
}
}
}]);
dire.directive("bannerloade", ["$timeout", function($timeout) { // 详情页轮播控制加载
    return {
        restrict: "EA",
        link: function(scope, element, attrs) {
            if (scope.$last == true) {
                $timeout(function() {
                    var swiper = new Swiper('.swiper-container', {
                        pagination: '.swiper-pagination',
                        paginationClickable: true,
                        spaceBetween: 30,
                    });

                }, 500);
            }
        }
    }
}]);
dire.directive("actives", ["$routeParams", '$sce', "$http", "surplusDay", function($routeParams, $sce, http, surplusDay) { // 活动列表
    return {
        templateUrl: "templates/groupbuy/active.html",
        restrict: "E",
        link: function(scope, element, attrs) {
            var product_id = $routeParams.product_id;
            http({
                method: 'GET',
                url: APIURL + 'app.php?c=goods&app=app&a=activity&product_id=' + product_id //活动列表
            }).success(function(data) {
                console.log(data);
                if (data.err_code == 20000) {
                    window.location = login_html;
                }
                scope.activity = data.err_msg;

            });
        }
    }
}]);
dire.directive("games", ["$routeParams", '$sce', "$http", "surplusDay", function($routeParams, $sce, http, surplusDay) { // 游戏列表
    return {
        templateUrl: "templates/groupbuy/game.html",
        restrict: "E",
        link: function(scope, element, attrs) {
            var product_id = $routeParams.product_id;
            http({
                method: 'GET',
                url: APIURL + 'app.php?c=goods&app=app&a=game&product_id=' + product_id //游戏列表
            }).success(function(data) {
                console.log(data);
                if (data.err_code == 20000) {
                    window.location = login_html;
                }
                scope.game = data.err_msg;

            });
        }
    }
}]);
dire.directive("createshop", ["$routeParams", '$sce', "$http", "surplusDay", function($routeParams, $sce, http, surplusDay) { // 创建分销商店铺
    return {
        templateUrl: "templates/groupbuy/createShop.html",
        restrict: "E",
        link: function(scope, element, attrs) {
            var store_id = $routeParams.store_id;
            http({
                method: 'GET',
                url: APIURL + 'app.php?c=drp&app=app&a=index&store_id=' + store_id //获取分销商店铺
            }).success(function(data) {
                if (data.err_code == 20000) {
                    window.location = login_html;
                }
                console.log(data);
                scope.createShop = data.err_msg;
                scope.agreement = $sce.trustAsHtml(scope.createShop.agreement); //分销协议
                $(".agreement i").click(function() {
                    $(this).toggleClass("active");
                });
                var num = new RegExp("^[0-9]*$"); //校验店铺名称
                var reg = /^0?1[3|4|5|8][0-9]\d{8}$/; //校验手机号码
                var patt = new RegExp("^[1-9]\\d{4,10}$"); //校验QQ号
                scope.createshopTime = function(a) {
                    scope.createShopShow = true;
                    scope.createShopTxt = a;
                    setTimeout(function() {
                        scope.createShopShow = false;
                        scope.$apply(scope.createShopShow);
                    }, 500);
                }
                scope.createShopButton = function() {
                    if (scope.shopName == undefined || scope.shopName == "") {
                        return scope.createshopTime("店铺名称不能为空!");
                    }
                    if (num.test(scope.shopName)) {
                        return scope.createshopTime("请输入合格店铺名称!");
                    }
                    if (scope.userTel == undefined || scope.userTel == "") {
                        return scope.createshopTime("手机号不能为空!");
                    }
                    if (!reg.test(scope.userTel)) {
                        return scope.createshopTime("请输入合格手机号!");
                    }
                    if (scope.userName == undefined || scope.userName == "") {
                        return scope.createshopTime("用户昵称不能为空!");
                    }
                    if (scope.userQQ == undefined || scope.userQQ == "") {
                        return scope.createshopTime("QQ号不能为空!");
                    }
                    if (!patt.test(scope.userQQ)) {
                        return scope.createshopTime("请输入合格QQ号!");
                    }
                    if (!$(".agreement i").hasClass("active")) {
                        return scope.createshopTime("亲阅读并同意《分销协议》!");
                    }
                    var data = {
                        store_id: store_id,
                        name: scope.shopName,
                        tel: scope.userTel,
                        linkname: scope.userName,
                        qq: scope.userQQ
                    };
                    console.log(data);
                    var transFn = function(data) {
                            return $.param(data);
                        },
                        postCfg = {
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                            },
                            transformRequest: transFn
                        };

                    http.post(APIURL + 'app.php?c=drp&app=app&a=register', data, postCfg).success(function(data) { //申请分销店铺
                        // console.log(data);
                        if (data.err_code == 0) {
                            //alert("申请分销商成功了!");
                            window.location = APIURL + "wap/ucenter.php?id=" + store_id + "#promotion"; //跳转到个人中心
                        }
                    });

                }


            });
        }
    }
}]);
dire.directive("shoplist", ["$routeParams", '$sce', "$http", "surplusDay", function($routeParams, $sce, http, surplusDay) { //门店列表页面
    return {
        templateUrl: "templates/groupbuy/shopList.html",
        restrict: "E",
        link: function(scope, element, attrs) {
            var store_id = $routeParams.store_id;
            http({
                method: 'GET',
                url: APIURL + 'app.php?c=store&app=app&a=physical&store_id=' + store_id //门店列表页面
            }).success(function(data) {
                if (data.err_code == 20000) {
                    window.location = login_html;
                }
                scope.shopList = data.err_msg;
                scope.reason = function(a) { //判断必选理由是否为空
                    if (a == "" || a == undefined) {
                        return false;
                    } else {
                        return true;
                    };
                };
                scope.workTime = function(a) { //判断营业时间是否为空
                    if (a == "" || a == undefined) {
                        return "09:00-18:00";
                    } else {

                    };
                }

            });
        }
    }
}]);
dire.directive("distribution", ["$routeParams", '$sce', "$http", "surplusDay", function($routeParams, $sce, http, surplusDay) { // 分销推广
    return {
        templateUrl: "templates/groupbuy/distribution.html",
        restrict: "E",
        link: function(scope, element, attrs) {
            var product_id = $routeParams.product_id;
            var store_id = $routeParams.store_id;
            scope.store_id = store_id;
            http({
                method: 'GET',
                url: APIURL + 'app.php?c=drp_ucenter&a=product_share&app=app&product_id=' + product_id + "&store_id=" + store_id //分销推广
            }).success(function(data) {
                console.log(data);
                if (data.err_code == 20000) {
                    window.location = login_html;
                }
                scope.distribution = data.err_msg;
                scope.linkShare = function() { //链接分享

                }
                scope.obtain = function() { //分销推广名片
                    http({
                        method: 'GET',
                        url: APIURL + 'app.php?c=drp_ucenter&app=app&a=store_qrcode&action=down&store_id=' + store_id //分销推广
                    }).success(function(data) {
                        console.log(data);
                        if (data.err_code == 0) {
                            window.location = data.err_msg;
                        }
                    })
                };

            });
        }
    }
}]);
